package com.hontlong.aixue.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import com.hontlong.aixue.bean.User;
import com.hontlong.aixue.bean.ZhiShi;

@Component
public class ZhiShiDao extends HibernateDaoSupport {
	private final Logger logger = org.slf4j.LoggerFactory
	.getLogger(ZhiShiDao.class);
	
	public void add(User user, String zhishiText) {
		ZhiShi zhishi=new ZhiShi();
		zhishi.setUsername(user.getUsername());
		zhishi.setContent(zhishiText);
		getHibernateTemplate().save(zhishi);
	}

	@SuppressWarnings("unchecked")
	public List<ZhiShi> list(final int pageIndex, final int pageSize) {
		logger.debug("pageIndex:{},pageSize:{}",pageIndex,pageSize);
		List<ZhiShi> some = (List<ZhiShi>) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						return session.createQuery(
								"from ZhiShi zhishi order by zhishi.id asc")
								.setFirstResult((pageIndex - 1) * pageSize)
								.setMaxResults(pageSize).list();
					}
				});
		return some;
	}

	@SuppressWarnings("unchecked")
	public List<ZhiShi> list(final String userName, final int pageIndex,
			final int pageSize) {
		List<ZhiShi> some = (List<ZhiShi>) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						return session
								.createQuery(
										"from ZhiShi zhishi where username=? order by zhishi.id asc")
								.setParameter(0, userName).setFirstResult(
										(pageIndex - 1) * pageSize)
								.setMaxResults(pageSize).list();
					}
				});
		return some;
	}

	public int total() {
	    Integer some = (Integer) getHibernateTemplate().execute(
			new HibernateCallback() {			    
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					return session.createQuery("select count(*) from ZhiShi").uniqueResult();
				}
			});
	    return some;
	}
}
